import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Streamlit应用标题
st.title('中国各省新冠疫情数据分析')

# 文件上传器
uploaded_file = st.file_uploader("上传CSV文件", type=["csv", "txt"])

def load_and_preview_data(file):
    data = pd.read_csv(file)
    st.write("数据预览")
    st.write(data.head())
    return data

def preprocess_data(data):
    if 'dateId' in data.columns:
        data['dateId'] = pd.to_datetime(data['dateId'], format='%Y%m%d')
    return data

def simple_statistics(data):
    st.write("### 统计数据")
    st.write(data.describe())

def calculate_average_confirmed_incr(data):
    if 'confirmedIncr' in data.columns:
        avg_confirmed_incr = np.mean(data['confirmedIncr'])
        st.write(f"### 平均每日新增确诊病例: {avg_confirmed_incr:.2f}")

def plot_trend(data, column, label, title, color='blue'):
    plt.figure(figsize=(10, 5))
    plt.plot(data['dateId'], data[column], label=label, color=color)
    plt.xlabel('日期')
    plt.ylabel(label.replace('Incr', '') + '数')
    plt.title(title)
    plt.legend()
    st.pyplot(plt)

def plot_province_trend(province_data, province_name):
    st.write(f"### {province_name} 累计确诊趋势图")
    plot_trend(province_data, 'confirmedCount', f'{province_name} 累计确诊', f'{province_name} 累计确诊趋势')
    st.write(f"### {province_name} 新增确诊趋势图")
    plot_trend(province_data, 'confirmedIncr', f'{province_name} 新增确诊', f'{province_name} 新增确诊趋势', color='red')

if uploaded_file is not None:
    try:
        data = load_and_preview_data(uploaded_file)
        data = preprocess_data(data)
        simple_statistics(data)
        calculate_average_confirmed_incr(data)

        if 'dateId' in data.columns and 'confirmedCount' in data.columns:
            st.write("累计确诊趋势图")
            plot_trend(data, 'confirmedCount', '累计确诊', '累计确诊趋势')

        if 'dateId' in data.columns and 'confirmedIncr' in data.columns:
            st.write("新增确诊趋势图")
            plot_trend(data, 'confirmedIncr', '新增确诊', '新增确诊趋势', color='red')

        if 'provinceName' in data.columns:
            provinces = data['provinceName'].unique()
            selected_province = st.selectbox('选择省份', provinces)
            province_data = data[data['provinceName'] == selected_province]
            plot_province_trend(province_data, selected_province)

    except Exception as e:
        st.error(f"发生错误：{e}")